import { Ref, ref, onMounted } from 'vue'
import CONFIG from '@/config'
import { postStart, postEnd, postHeartBeat } from '@/api/roomApi'
import { AUTH_CODE, BiliResponseType, RoomInfoType } from '@/types/types'
import { closeSSW, openSSW } from '@/module/Socket'
import { ElMessage } from 'element-plus'

  //连接直播间成功后返回的信息
  const roomInfo: Ref<BiliResponseType<RoomInfoType> | undefined>= ref(undefined)
  const isstart = ref(false)
  const isloading = ref(false)

  //心跳interval
  let timer: NodeJS.Timer
  //获取房间信息
  const linkRoomModule = (code?: string): number => {
    if(roomInfo.value == undefined){
      let params = {
          "code": !code ? CONFIG.CODE : code ,
          "app_id": CONFIG.APP_ID 
        }

      postStart(JSON.stringify(params))
      .then(({ data }) => {
          if(roomInfo.value == undefined && data.code == 0){
            roomInfo.value = data 
            //启动心跳
            timer = setInterval(() => {
              heartBeatModule();
            }, 20000)
            console.log("[room] 房间信息获取 成功")
            //websocket
            openSSW(data.data)
            
          }
          else{
            isloading.value = false
            console.log("[room] 房间信息获取 连接服务器失败 " + data.code)
            
            ElMessage({
              message: '获取房间信息失败：' + AUTH_CODE["CODE_" + data.code],
              type: 'error',
            })
            return data.code
          }
      })
      .catch((err) => {
        isloading.value = false
        console.log("[room] 房间信息获取 异常捕获")
        ElMessage({
          message: '获取房间信息失败：' + '请联系开发人员',
          type: 'error',
        })
        console.error(err)
        endRoomModule()
        return -1
      })
    }
    else {
      isloading.value = false
      console.log("[room] 房间信息获取 正在连接")
      return -2
    }
    return 0
  }

  //发送心跳包
  const heartBeatModule = () => {
    if(roomInfo.value != undefined){
      let params = {
        "game_id": roomInfo.value.data.game_info.game_id 
      }

      postHeartBeat(JSON.stringify(params))
          .then(({ data }) => {
            if(data.code == 0) {
              console.log("[room] 心跳 成功")
            }
            else {
              console.log("[room] 心跳 连接服务器失败: " + data.code)
              ElMessage({
                message: '心跳失败：' + AUTH_CODE["CODE_" + data.code],
                type: 'error',
              })
              return data.code
            }
          })
          .catch((err) => {
              console.log("[room] 心跳 异常捕获")
              ElMessage({
                message: '心跳失败：' + '请联系开发人员',
                type: 'error',
              })
              console.error(err)
              return -1
          });
    }
    else {
      console.log("[room] 心跳 失败：房间信息为空")
      return -2
    }
    return 0
  }

  //关闭连接
  const endRoomModule = () => {
    if(roomInfo.value != undefined){
      let params = {
        "app_id": CONFIG.APP_ID,
        "game_id": roomInfo.value.data.game_info.game_id 
      }

      postEnd(JSON.stringify(params))
          .then(({ data }) => {
              if(data.code == 0) {
                clearInterval(timer)
                roomInfo.value = undefined
                closeSSW()
                console.log("[room] 关闭 成功")
                ElMessage({
                  message: '房间关闭成功',
                  type: 'success',
                })
              }
              else {
                console.log("[room] 关闭 连接服务器失败: " + data.code)
                return data.code
              }
          })
          .catch((err) => {
              console.log("[room] 关闭 异常捕获")
              console.error(err)
              return -1
          });
    }
    else {
      console.log("[room] 关闭 失败：房间信息为空")
      return -2
    }
    return 0
  }

  const getRoomInfo = (): BiliResponseType<RoomInfoType> | undefined => {
    return roomInfo.value
  }

  const setStart = (b: boolean) => {
    isstart.value = b
  }
  const getStart = () => {
    return isstart.value
  }

export { linkRoomModule, getRoomInfo, endRoomModule, heartBeatModule, getStart, setStart, isloading, isstart }

